//var db = openDB();
/*$(document).ready(function(){
	initCaseList();
});*/
var jsonary={};
var docIndex=0;
var docToal=0;
function initCaseeList(){
	$("#datagrid-toolbar #queryCaseBasicInfoForm #caseNumber").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #caseStep").combobox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #party").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #caseStartTime").datebox({});
	$("#datagrid-toolbar #queryCaseBasicInfoForm #caseEndTime").datebox({});
	
	/*$("#datagrid-toolbar #queryCaseBasicInfoForm #organName").textbox();*/
	$("#datagrid-toolbar #queryCaseBasicInfoForm #fillingPlace").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #staff").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #zfml").combobox();
	
	$("#datagrid-toolbar #queryCaseBasicInfoForm #caseName").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #illegalFacts").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #punishLaw").textbox();
	$("#datagrid-toolbar #queryCaseBasicInfoForm #illegalLaw").textbox();
	/**
	 * 获得机构对应的环节
	 */
	findLinkNameByOid(organId,'1',initCaseStep);
	/**
	 * 初始化案件类型
	 */
	findOrganZfmlByOrganIdOffLine(organId,initCaseZfml);
	/**
	 *刷新按钮设置
	 */
	$("#datagrid-toolbar #reload_link").linkbutton({
	    iconCls: 'icon-reload',
	    plain:true,
	    onClick:function(){
	    	searchCaseBasicInfo(new page());
        }
	});
	
	$("#datagrid-toolbar #report").linkbutton({
	    iconCls: 'icon-reload',
	    plain:true,
	    onClick:function(){
	    	var condition=getCondition();
	    	$('#reportWin').window({   
	    		title:'案件统计报表',
	    		top:200,
	    		left:200,
	    	    width:600,    
	    	    height:400,
	    	    minimizable:true,
	    	    maximizable:true,
	    	    closable:true,
	    	    modal:true,
	    	    href:getContextPath() + "/report/gethtmlCaseReport",
	    	    queryParams:condition
	    	});  
        }
	});
	$("#datagrid-toolbar #xlsexport").linkbutton({
	    iconCls: 'icon-reload',
	    plain:true,
	    onClick:function(){
	    $("#queryCaseBasicInfoForm").attr("action",getContextPath()+"/report/getxlsCaseReport");
		$("#queryCaseBasicInfoForm").submit();
        }
	});
	$("#datagrid-toolbar #pdfexport").linkbutton({
	    iconCls: 'icon-reload',
	    plain:true,
	    onClick:function(){
	    $("#queryCaseBasicInfoForm").attr("action",getContextPath()+"/report/getPDFCaseReport");
		$("#queryCaseBasicInfoForm").submit();
        }
	});
	/**
	 *查询按钮设置
	 */
	$("#datagrid-toolbar #search").linkbutton({
	    iconCls: 'icon-search',
	    plain:true,
	    onClick:function(){
	    	searchCaseBasicInfo(new page());
        }
	});
	
	$("#datagrid-toolbar #reset").linkbutton({
		plain:true,
		onClick:function(){
			$('#queryCaseBasicInfoForm').form('reset');
        }
	});
	
	/**
	 *修改按钮设置
	 */
	$("#datagrid-toolbar #edit_link").linkbutton({
	    iconCls: 'icon-edit',
	    plain:true,
	    onClick:function(){
        	var row = getSelectedRow('#datagrid');
        	if(!row){
    			return;
    		}
        	$("#main").removeClass("panel-noscroll");
        	$("#main").load("../register/caseBasicInfoInput.html",function(){
        		$("#caseBasicInfoForm #id").val(row.id);
        		$("#caseBasicInfoForm #caseCauseId").val(row.caseCauseId);
    			findDrawerById(row.zfmlId, initCase);
    		});
        }
	});
	
	/**
	 *办理按钮设置
	 */
	$("#datagrid-toolbar #handle_link").linkbutton({
	    onClick:function(){
        	var row = getSelectedRow('#datagrid');
        	if(!row){
    			return;
    		}
        	
        	$("#main").load("../register/handle.html",function(){
        		initCaseHandle(row);
        	});
        }
	});
	
	/**
	 *回传按钮设置
	 */
	
	if(!online){
		/**
		 * 回传
		 */
		$("#datagrid-toolbar #return_link").linkbutton({
		    iconCls: 'icon-undo',
		    plain:true,
		    onClick:function(){
	        	retur();
	        }
		});
		$("#datagrid-toolbar #report").hide();
		$("#datagrid-toolbar #xlsexport").hide();
		$("#datagrid-toolbar #pdfexport").hide();
	}else{
		$("#datagrid-toolbar #return_link").hide();
	}
	
	searchCaseBasicInfo(new page());
	$("#caseQuickSousuo").unbind().bind('click',function(){
//		$("#gzt,#dbsx").trigger("click");
//		$("#gzt li").trigger("click");
		//searchCaseBasicInfo(new page());
		
		$("#caseQuickSousuo").unbind('click').bind('click',function(){
			var casequick_= $("#caseQuick").val();
			if(casequick_ == '结案'){
				$("#main").load("../register/list.html",function(){
					$("#ajzx li").trigger("click");
					$("#report").hide();
					$("#xlsexport").hide();
					$("#pdfexport").hide();
					$("#operate_flag").val("ajzx");
					initCaseeList();
				});
			}else{
				$("#th").hide();
				$("#main").load("../register/list.html",function(){
					$("#gzt li").trigger("click");
					$("#noJa").val("结案");
					$("#noCxgd").val("撤销归档");
					$("#report").hide();
					$("#xlsexport").hide();
					$("#pdfexport").hide();
					$("#operate_flag").val("");
					initCaseeList();
				});
			}
			
		});
	});
	
	
	
	/**
	 * 文本框变化显示查询结果
	 */
	conditionChangeAutoList();
	
}




/**
 * 文本框变化显示查询结果
 */
function  conditionChangeAutoList(){
	
	
	$("#caseNumber,#party,#fillingPlace,#staff,#caseName,#illegalFacts,#punishLaw,#illegalLaw").textbox({
		 onChange:function(){
			  if(online){
					 search1(page);
					 }else{
					 search2(page);
					 }
		  }
		});	
	
	$("#caseStep,#zfml").combobox({
	   onSelect:function(){
			  if(online){
					 search1(page);
					 }else{
					 search2(page);
					 }
		  }
	});
	
	
	$("#caseStartTime,#caseEndTime").datebox({
		   onSelect:function(){
				  if(online){
						 search1(page);
						 }else{
						 search2(page);
						 }
			  }
		});
	
}





/**
 *初始化案件环节
 */
function initCaseStep(data){
	if($.trim($("#noJa").val()).length!=0){
		/**
		 * 删除最后一个元素
		 */
		data.pop();
	}
	/**
	 * 初始化环节
	 */
    if($.trim($("#operate_flag").val()).length!=0){
    	$("#queryCaseBasicInfoForm #caseStep").combobox({
    		valueField: 'linkName',
    		textField: 'linkName',
    		data:[{
    			linkName: '结案',
    			linkName: '结案'
    		}],
    		editable:false,
    		value:'结案',
    		panelHeight:'auto'
    	});
	}else{
		$("#queryCaseBasicInfoForm #caseStep").combobox({
			valueField: 'linkName',
			textField: 'linkName',
			data:data,
			editable:false,
			panelHeight:'auto'
		});
	}
}

function initCaseZfml(data){
	$("#queryCaseBasicInfoForm #zfml").combobox({
		valueField: 'zfml',
		textField: 'zfml',
		data:data,
		editable:false,
		panelHeight:'auto'
	});
}

/**
 * 定义分页全局变量
 */
var page_caseBasicInfo= new page({search:searchCaseBasicInfo,callback:func});

/**
 * 定义容器全局变量
 */
var con_caseBasicInfo = new container({
	datagrid:'#datagrid',
	datagridtoolbar:'#datagrid-toolbar', 
	singleSelect:true});

/**
 * 获取查询条件
 * @returns {condition}
 */
function getCondition(){
	var condition = $("#tb #queryCaseBasicInfoForm").serializeJson();
	condition.organId = organId;
	if($.trim($("#operate_flag").val()).length != 0 && $("#operate_flag").val() == "ajzx"){
		condition.caseStep="结案";
	}
	return condition;
}

function getCondition_quick(){
	var condition ={};
	condition.organId = organId;
	condition.caseQuick=$("#caseQuick").val();
	var noJa=$("#noJa").val();
	if($.trim(noJa).length!=0){
		condition.noJa=noJa;
    }else{
    	condition.noJa="";
    }
	return condition;
}

 function searchCaseBasicInfo(page){
  if(online){
	 search1(page);
	 }else{
	 search2(page);
	 }
 }

/**
 * 查询
 * @param page
 */
function search1(pg){
	var url = getContextPath() + "/caseBasicInfo/queryCaseBasicInfos_";
//	var url = getContextPath() + "/caseBasicInfo/queryCaseBasicInfos";
	page_caseBasicInfo.pageSize = pg.pageSize;
	page_caseBasicInfo.pageNumber = pg.pageNumber;
	if($.trim($("#caseQuick").val()).length!=0){
		query(url, getCondition_quick(), con_caseBasicInfo, page_caseBasicInfo);
	}else{
		query(url, getCondition(), con_caseBasicInfo, page_caseBasicInfo);
	}
	
}

function search2(pg){
	page_caseBasicInfo.pageSize = pg.pageSize;
	page_caseBasicInfo.pageNumber = pg.pageNumber;
	if($.trim($("#caseQuick").val()).length!=0){
		findAllCaseBasicInfoOffLine(getCondition_quick(),con_caseBasicInfo,page_caseBasicInfo);
	}else{
		findAllCaseBasicInfoOffLine(getCondition(),con_caseBasicInfo,page_caseBasicInfo);
	}
}

/**
 * 回调函数
 */
function func(){
	$("#datagrid").datagrid({onClickRow:function(index,row){
		if(row.caseStep!='信息登记'){
			$('#datagrid-toolbar #edit_link').linkbutton('disable');
		}else{
			$('#datagrid-toolbar #edit_link').linkbutton('enable');
		}
	},
	onSelect:function(index,row){
		if(row.caseStep!='信息登记'){
			$('#datagrid-toolbar #edit_link').linkbutton('disable');
		}else{
			$('#datagrid-toolbar #edit_link').linkbutton('enable');
		}
	}});
}
/**
 * 获取在线案件列表
 * @param condition 查询条件
 * @param page  分页信息
 * @param callback 回调函数
 */
/*function queryCaseBasicInfos(condition, page, callback){
	condition.page = page.pageNumber;
	condition.size = page.pageSize;
	$.ajax({
        type: "get",
        url:getContextPath()+"/caseBasicInfo/queryCaseBasicInfos",
        dataType:"json",
        data:condition,
        success: function(data) {
        	page.data.total = data.totalElements;
        	page.data.rows  = data.content;
        	if(typeof(callback) == 'function')
        		callback(page);
        },
        error: function(request) {
            message("获取案件列表失败");
        }
    });
}*/

/**
 * 查询
 *//*
function search(){
	if(online){
		*//**
		 * 获取在线案件列表
		 **//*
		queryCaseBasicInfos(getCondition(), page, init);
	}else{
		*//**
		 * 获取离线案件列表
		 **//*
		findAllCaseBasicInfoOffLine(getCondition(), page, init);
	}
}
*/
/**
 * 获得回传离线数据
 */
function retur(){
	var row = getSelectedRow('#datagrid');
	if(!row){
		return;
	}
	
	if(!navigator.onLine){
		message("当前网络不可用");
		return;
	}
	
	$.messager.confirm('提示', '确定要回传吗?', function(bool){
	    if (bool){
	    	docIndex=0;
	    	 for(var item in row){  
	    		 if($.trim(row[item])==""){
	    			row[item]=null;
	    		 }
	    	 }
	    	jsonary={};
	    	jsonary.caseBasicInfo=row;
	    	jsonary.flag="1";//案件回传
	    	//通过机构ID获取文书
	    	findDocsByOid(organId,docSum);
	    	//findCaseBasicInfoByIdOffLine(row.id,returnCaseBasicInfoOnLine);
	    }
	});
}
/**
 * 查询本机构关联的所有文书总数（包含明细）
 * @param data
 */
function docSum(data){
	var func="countDocToal";
	window[func](data,docAry);
}

function countDocToal(data,callback){
	docToal=data.length;
	$.each(data,function(index,item){
		var docPath = item.docPath.substring(0,item.docPath.indexOf("Input."));
		if(docPath=="caseProcessIdea" ||docPath=="entrustIdentify"||docPath=="evidenceList"||docPath=="documentReceipt"||docPath=="sampleEvidence"){
			docToal+=1;
		}
	});
	if(typeof(callback) == 'function'){
    	callback(data);
    }
}

/**
 * 封装文书数据
 * @param data
 */
function docAry(data){
	var row = getSelectedRow('#datagrid');
	$.each(data,function(index,item){
		var docPath = item.docPath.substring(0,item.docPath.indexOf("Input."));
		var docPathLen = item.docPath.length;
		if(docPathLen > 0){
				var first = docPath.substring(0,1).toUpperCase();
				var last = docPath.substring(1,docPathLen);
				var func= "find" + first + last + "ByIdOffLine";
				window[func](row.id,docToJsonArray);
		}
   });
}
function docToJsonArray(data,formId){
	docIndex+=1;
	var docName = formId.substring(1,formId.indexOf("Form"));
	if(data !=null && data!=undefined && data!=''){
		if(data instanceof Array){
			$.each(data,function(index,obj){
				for(var item in obj){  
		    		 if($.trim(obj[item])==""){
		    			 delete obj.item;
		    			obj[item]=null;
		    		 }
		    	 }
			});
		}else{
			 for(var item in data){  
	    		 if($.trim(data[item])==""){
	    			 delete data.item;
	    			data[item]=null;
	    		 }
	    	 }
		}
		jsonary[docName]=data;
	}
	if(docName=="caseProcessIdea" ||docName=="entrustIdentify"||docName=="evidenceList"||docName=="documentReceipt"||docName=="sampleEvidence"){
		if(data !=null && data!=undefined && data!=''){
			var docPathLen =docName.length;
			var first = docName.substring(0,1).toUpperCase();
			var last = docName.substring(1,docPathLen);
			var func= "findAll" + first + last + "DetailByIdOffLine";
			window[func](data,docToJsonArray);
			
		}else{
			docIndex+=1;
		}
	}
	if(docIndex==docToal){
		returnCaseBasicInfoOnLine(jsonary);
      }
}

/**
 * 回传离线数据
 * @param caseBasicInfo
 */
function returnCaseBasicInfoOnLine(data){
	
	if(data.caseBasicInfo.isOnLine == '在线'){
		message("案件信息已经回传");
		return;
	}
	var id = data.caseBasicInfo.id;
	delete data.caseBasicInfo.isOnLine;
	
	$.ajax({
		type : "POST",
		url :ctx+ "/caseBasicInfoRe/add",
		dataType : "json",
		data :JSON.stringify(data),
	    contentType:'application/json;charset=UTF-8',
		success : function(data) {
			if(data.result == 'success'){
				//setDataId(data.caseBasicInfo,"#caseBasicInfoForm");
				message("案件信息回传成功");
				/**
				 *将websql中的案件ISONLINE修改为在线
				 */
				updateCaseBasicInfoIsOnLineOffLine(id,'在线',searchCaseBasicInfo);
				
			}else{
				message(data.errorCode + ":" +data.errorMessage);
			}
		}
	 });
}



/**
 * 初始化案件列表
 * @param data
 * @param page
 */
/*function init(page){
	$(con.datagrid).datagrid({
		border:false,
		fitColumns:true,
		checkbox:true,
		fit:true,
		remoteSort:false,
		rownumbers:true,
		singleSelect:con.singleSelect,
		toolbar: con.datagridtoolbar,
		pagination:con,
		loadFilter:pagerFilter}).datagrid('loadData', page.data);
	*//**
	 * 设置列表
	 *//*
	datagd(page.data,'#datagrid','#datagrid-toolbar');
	
	$('#datagrid').datagrid({onClickRow:function(rowIndex, rowData){
		if(rowData.caseStep!='信息登记'){
			$('#datagrid-toolbar #edit_link').linkbutton('disable');
		}else{
			$('#datagrid-toolbar #edit_link').linkbutton('enable');
		}
	}});
	
	*//**
	 * 设置分页
	 *//*
	pagination('#datagrid', page, search);
}*/

/**
 * 添加测试数据
 */
function addCaseBasicInfoTest(){
	for(var i=1;i<58;i++){
		var dataTest = {};
		dataTest.caseNumber = "案件编号".concat(i);
		dataTest.caseStep = "信息登记";
		dataTest.executionType = "执行类型".concat(i);
		dataTest.fillingDate = "2012-09-09 14:50:40";
		dataTest.fillingPlace = "立案地点".concat(i);
		dataTest.party = "当事人".concat(i);
		dataTest.staff1 = "执法人ONE".concat(i);
		dataTest.staff2 = "执法人TWO".concat(i);
		dataTest.zfml = "执法门类".concat(i);
		dataTest.organId = 1;
		saveCaseBasicInfoTest(dataTest);
	}
}

/**
 *设置表头
 */
/*var columns = [[
	      {field:'ck',checkbox:true,rowspan:2},
	      {field:'id',title:'ID',hidden:true,align:'center',width:50,rowspan:2},
	      {field:'caseNumber',title:'案件编号',align:'center',width:100,sortable:true,rowspan:2},
	      {field:'fillingPlace',title:'立案地点',align:'center',width:150,sortable:true,rowspan:2},
	      {field:'fillingDate',title:'立案时间',align:'center',width:100,sortable:true,rowspan:2},
	      {field:'party',title:'当事人',align:'center',width:60,sortable:true,rowspan:2},
	      {field:'executionType',title:'执行类型',align:'center',width:70,sortable:true,rowspan:2},
	      {field:'zfml',title:'执法门类',align:'center',width:100,sortable:true,rowspan:2},
	      {title:'执法人',align:'center',width:150,sortable:true,colspan:2},
	      {field:'caseStep',title:'当前环节',align:'center',width:30,sortable:true,rowspan:2}
      ],
      [
      	  {field:'staff1',title:'执法人1',align:'center',width:75,sortable:true},
          {field:'staff2',title:'执法人2',align:'center',width:75,sortable:true}]];*/
